/*
	SquirrelUtils.c
	--------------------------------------------------
	Utils to push LU class instances (Players, Vehicles...)
	to the Squirrel VM stack.
*/

#include "SquirrelUtils.h"
#include "SQModule.h"
#include <stdio.h>

extern SQAPI sq;

SQInteger release_hook( SQUserPointer p, SQInteger size )
{
	return 1;
}

__inline void sq_pushclassinstance( HSQUIRRELVM v, SQUserPointer p, const SQChar* type )
{
	SQInteger stack = sq->gettop( v );

	sq->pushroottable( v ); // Get the class created with sq_newclass
	sq->pushstring( v, type, -1 );
	sq->rawget( v, -2 );

	sq->createinstance( v, -1 ); // Create an instance of the class on top of the stack
	sq->remove( v, -3 );
	sq->remove( v, -2 );

	if ( SQ_FAILED( sq->setinstanceup( v, -1, p ) ) )
	{
		// If the instance couldn't be created push null instead
		sq->settop( v, stack );
		sq->pushnull( v );
	}

	sq->setreleasehook( v, -1, release_hook );
}

void sq_pushplayerpointer( HSQUIRRELVM v, SQUserPointer p )
{
	sq_pushclassinstance( v, p, _SC( "Player" ) );
}

void sq_pushvehiclepointer( HSQUIRRELVM v, SQUserPointer p )
{
	sq_pushclassinstance( v, p, _SC( "Vehicle" ) );
}

void sq_pushobjectpointer( HSQUIRRELVM v, SQUserPointer p )
{
	sq_pushclassinstance( v, p, _SC( "Object" ) );
}

void sq_pushpickuppointer( HSQUIRRELVM v, SQUserPointer p )
{
	sq_pushclassinstance( v, p, _SC( "Pickup" ) );
}

void sq_pushcheckpointpointer( HSQUIRRELVM v, SQUserPointer p )
{
	sq_pushclassinstance( v, p, _SC( "Checkpoint" ) );
}

void sq_pushspherepointer( HSQUIRRELVM v, SQUserPointer p )
{
	sq_pushclassinstance( v, p, _SC( "Sphere" ) );
}

void sq_pushblippointer( HSQUIRRELVM v, SQUserPointer p )
{
	sq_pushclassinstance( v, p, _SC( "Blip" ) );
}

void sq_pushspawnclasspointer( HSQUIRRELVM v, SQUserPointer p )
{
	sq_pushclassinstance( v, p, _SC( "SpawnClass" ) );
}

void sq_pushsoundpointer( HSQUIRRELVM v, SQUserPointer p )
{
	sq_pushclassinstance( v, p, _SC( "Sound" ) );
}

void sq_pushvector3pointer( HSQUIRRELVM v, SQUserPointer p )
{
	sq_pushclassinstance( v, p, _SC( "Vector" ) );
}
